/**
 * 认证 Store
 * 管理用户登录状态、用户信息、权限等
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api/modules/auth'
import { setToken, getToken, removeToken, setUserInfo, getUserInfo as getStoredUserInfo, removeUserInfo, clearAuth } from '@/utils/storage'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(getToken() || '')
  const userInfo = ref(getStoredUserInfo() || null)
  const permissions = ref([])
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const hasPermission = (permission) => {
    if (!permission) return true
    if (permissions.value.includes('*:*:*')) return true
    return permissions.value.includes(permission)
  }
  
  /**
   * 登录
   * @param {object} loginData 登录数据
   */
  async function login(loginData) {
    try {
      const data = await loginApi(loginData)
      
      // 保存 token 和用户信息
      token.value = data.token
      userInfo.value = data.user
      setToken(data.token)
      setUserInfo(data.user)
      
      ElMessage.success('登录成功')
      return true
    } catch (error) {
      ElMessage.error(error.message || '登录失败')
      return false
    }
  }
  
  /**
   * 获取用户信息
   */
  async function getUserInfo() {
    try {
      const data = await getUserInfoApi()
      userInfo.value = data
      permissions.value = data.permissions || []
      setUserInfo(data)
      return data
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  }
  
  /**
   * 登出
   */
  async function logout() {
    try {
      await logoutApi()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      // 清空状态
      token.value = ''
      userInfo.value = null
      permissions.value = []
      clearAuth()
      
      ElMessage.success('已退出登录')
    }
  }
  
  /**
   * 重置状态
   */
  function resetState() {
    token.value = ''
    userInfo.value = null
    permissions.value = []
    clearAuth()
  }
  
  return {
    // 状态
    token,
    userInfo,
    permissions,
    
    // 计算属性
    isLoggedIn,
    
    // 方法
    login,
    getUserInfo,
    logout,
    resetState,
    hasPermission
  }
})

